package com.yanghongyue.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yanghongyue.reggie.bean.Dish;
import com.yanghongyue.reggie.bean.Flavor;
import com.yanghongyue.reggie.bean.dto.DishDto;
import com.yanghongyue.reggie.mapper.DishMapper;
import com.yanghongyue.reggie.mapper.FlavorMapper;
import com.yanghongyue.reggie.service.DishService;
import com.yanghongyue.reggie.service.FlavorService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author HongyueYang
 */
@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish>implements DishService {

    @Autowired
    private FlavorService flavorService;


    //新增菜品
    @Override
    @Transactional
    public void saveDish(DishDto dto) {
        //给菜品设置排序
        dto.setSort(1);
        //保存菜品
        this.save(dto);
        //获取dto对象中的口味集合
        List<Flavor> flavors = dto.getFlavors();
        //遍历集合
        for (Flavor flavor : flavors) {
            //给口味对象设置所属菜品id
            flavor.setDishId(dto.getId());
        }
        //批量保存口味
        flavorService.saveBatch(flavors);

    }


    //根据id查询菜品及其对应的口味信息
    @Override
    public DishDto getDishWithFlavors(Long id) {

        //根据id查询菜品信息
        Dish dish = this.getById(id);
        //创建Dto对象
        DishDto dishDto = new DishDto();
        //将菜品信息复制到dto对象中
        BeanUtils.copyProperties(dish,dishDto);
        //创建条件构造器
        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.eq("dish_id",id);
        //根据菜品id查询口味信息集合
        List<Flavor> flavors = flavorService.list(wrapper);
        //将口味集合设置给dto对象
        dishDto.setFlavors(flavors);
        return dishDto;
    }

    //修改菜品信息
    @Override
    @Transactional
    public void updateDishWithFlavors(DishDto dto) {
        //修改菜品信息
        this.updateById(dto);
        //根据id删除口味信息
        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.eq("dish_id",dto.getId());
        flavorService.remove(wrapper);
        //获取dto对象中的口味集合
        List<Flavor> flavors = dto.getFlavors();
        //遍历集合
        for (Flavor flavor : flavors) {
            //给口味对象设置所属菜品id
            flavor.setDishId(dto.getId());
        }
        //批量保存口味
        flavorService.saveBatch(flavors);


    }


}
